# coding=gbk
import scipy.sparse as sp
import sys
import numpy
import unittest

def get_cosine_sim(matrix):
    sq_sum = numpy.multiply(matrix, matrix).sum(1)
    sq_sum = sq_sum * sq_sum.T
    matrix = sp.csc_matrix(matrix)
    matrix = (matrix * matrix.T).todense()
    numpy.divide(matrix, numpy.power(sq_sum, 0.5,sq_sum), matrix)
    return matrix

# this is not used ..
# because the matrix is not a sparse matrix any more after adjusted
#def get_adjusted_cosine_sim(matrix):
#    matrix -= matrix.mean(0)
#    return get_cosine_sim(matrix)


# need a dense matrix, return a csc_matrix
# k neareast neibour .. will modify the sim_mat
def knn(sim_mat, k):
    size = sim_mat.shape[1]
    sim_mat[sim_mat<sim_mat[range(0,size),sim_mat.argsort()[:, size - k -1].T].T.repeat(size, 1)]=0
    return sim_mat

def get_recommend_matrix( sim_mat,user_mat):
    orig_mat= user_mat
    item_cnt=user_mat.shape[1]
    matrix=sim_mat.sum(1)
    user_mat = (sp.csc_matrix(sim_mat) * sp.csc_matrix(user_mat)).todense()
    matrix = numpy.divide(user_mat, matrix)
    return matrix
